package cn.gov.msa.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 解析注解上的spring EL 值 @DZZWCacheEvict(value="dzzw_cache",key="#menuPermission[0].roleCode")
 * SPEL
 * @author Administrator
 *
 */
@Component
public class DefaultKeyGenerator{
	
	public String  generateKey(JoinPoint jp, String value, String key) throws NoSuchMethodException { 
		if(StringUtils.isEmpty(key))
			throw new NullPointerException("CacheKey can not be null...");
		Signature signature = jp.getSignature(); 
	 
		String results =null; 
		//解析cacheKey
		EvaluationContext evaluationContext = new StandardEvaluationContext(); 
		if (!(signature instanceof MethodSignature)) { 
			throw new IllegalArgumentException("This annotation can only be used for methods..."); 
			} 
		MethodSignature methodSignature = (MethodSignature) signature; 
		//method参数列表 
		String[] parameterNames = methodSignature.getParameterNames(); 
		Object[] args = jp.getArgs(); 
		for(int i = 0; i < parameterNames.length; i++){ 
			String parameterName = parameterNames[i]; 
			evaluationContext.setVariable(parameterName, args[i]); 
			} 
			results  = new SpelExpressionParser().parseExpression(key).getValue(evaluationContext, String.class);
		return results; 
		}
	}